<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        :placeholder="$t('category.name')"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >{{ $t('table.search') }}</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="success"
        icon="el-icon-circle-plus-outline"
        @click="handleCreate('0')"
      >
        {{
        $t('table.add')
        }}
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      row-key="id"
      :data="list"
      stripe
      border
      fit
      highlight-current-row
      style="width: 100%;"
      lazy
      ref="table"
      :load="load"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column :label="$t('category.name')" min-width="120px">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('category.description')" min-width="120px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('category.status')" class-name="status-col" width="80">
        <template slot-scope="{ row }">
          <el-tag :type="row.status === 0 ? 'success' : 'danger'">{{ row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('category.gmtModified')" width="160px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.gmtModified | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230px">
        <template slot-scope="{ row, $index }">
          <el-button
            type="success"
            size="mini"
            @click="handleCreate(row.id)"
          >{{ $t('category.addChild') }}</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">{{ $t('table.edit') }}</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="80px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item :label="$t('category.name')" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item :label="$t('category.description')" prop="description">
          <el-input v-model="temp.description" />
        </el-form-item>
        <el-form-item :label="$t('category.sort')" prop="sort">
          <el-input v-model="temp.sort" />
        </el-form-item>
        <el-form-item :label="$t('category.status')" prop="status">
          <el-switch
            style="display: block"
            v-model="temp.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createCategory, updateCategory, deleteCategory } from '@/api/category'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'

const statusOptions = [
  {
    value: 0,
    label: '启用'
  },
  {
    value: 1,
    label: '禁用'
  }
]

export default {
  name: 'CategoryTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      for (let i = 0; i < statusOptions.length; i++) {
        var item = statusOptions[i]
        if (status === item.value) {
          return item.label
        }
      }
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: '',
        pid: '0'
      },
      showReviewer: false,
      temp: {
        name: '',
        description: '',
        sort: '',
        status: '',
        pid: '',
        gmtModified: new Date()
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      statusOptions: statusOptions,
      rules: {
        name: [{ required: true, message: 'name is required', trigger: 'blur' }],
        sort: [{ required: true, message: 'sort is required', trigger: 'blur' }],
        status: [{ required: true, message: 'status is required', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        name: '',
        description: '',
        sort: '',
        status: '',
        pid: '',
        gmtModified: new Date()
      }
    },
    handleCreate(id) {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp.pid = id
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createCategory(this.temp)
            .then(response => {
              if (response.code === 1) {
                if (this.temp.pid === '0') {
                  this.handleFilter()
                } else {
                  let data = response.data
                  const index = this.list.findIndex(v => v.id === data.pid)
                  this.list[index].hasChildren = true
                  if (this.list[index].children === undefined) {
                    this.list[index].children = []
                  }
                  this.list[index].children.push(data)
                }
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '失败',
                  message: '创建失败',
                  type: 'error',
                  duration: 2000
                })
              }
            })
            .catch(() => {
              this.$notify({
                title: '异常',
                message: '创建异常',
                type: 'error',
                duration: 2000
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.temp.hasChildren = this.temp.hasChildren ? 1 : 0
          updateCategory(this.temp).then(response => {
            const { code, data } = response
            if (code === 1) {
              this.temp.gmtModified = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
              if (this.temp.pid == '0') {
                const index = this.list.findIndex(v => v.id === this.temp.id)
                this.list.splice(index, 1, this.temp)
              } else {
                const index = this.list.findIndex(v => v.id === data.pid)
                const cindex = this.list[index].children.findIndex(v => v.id === data.id)
                this.list[index].children.splice(cindex, 1, data)
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '更新失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.temp = Object.assign({}, row)
        this.temp.hasChildren = this.temp.hasChildren ? 1 : 0
        deleteCategory(this.temp)
          .then(response => {
            const { code } = response
            if (code === 1) {
              if (this.temp.pid === '0') {
                this.handleFilter()
              } else {
                const index = this.list.findIndex(v => v.id === this.temp.pid)
                const cindex = this.list[index].children.findIndex(v => v.id === this.temp.id)
                this.list[index].children.splice(cindex, 1)
                if (this.list[index].children.length === 0) {
                  this.list[index].hasChildren = false
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '删除失败',
                type: 'error',
                duration: 2000
              })
            }
          })
          .catch(() => {
            this.$notify({
              title: '异常',
              message: '删除数据出现异常',
              type: 'error',
              duration: 2000
            })
          })
      }).catch(() => {})
    },
    load(tree, treeNode, resolve) {
      this.temp.pid = tree.id
      let query = {
        page: 0,
        limit: 0,
        name: '',
        pid: tree.id
      }
      fetchList(query)
        .then(response => {
          if (response.code === 1) {
            const index = this.list.findIndex(v => v.id === this.temp.pid)
            this.list[index].children = response.data
            resolve(response.data)
          } else {
            his.$notify({
              title: '失败',
              message: '数据加载失败',
              type: 'error',
              duration: 2000
            })
          }
        })
        .catch(() => {
          this.$notify({
            title: '异常',
            message: '数据加载异常',
            type: 'error',
            duration: 2000
          })
        })
    }
  }
}
</script>
